/**
 * @file form
 * @author liaoxuezhi@baidu.com
 */
/* eslint fecs-indent: [0, "space", 2, 2] */

import * as React from 'react';
import {
  Component,
  PureComponent,
  PropTypes
} from 'react';
import {findDOMNode} from 'react-dom';
import {Renderer, render} from '../../renderer';
import * as cx from 'classnames';
import * as assign from 'object-assign';
import {Enhance as HocCrud} from '../hoc-crud';
import {padArr} from '../../util';

import './card';
import './card-action';
import './grid.scss';
import '../table/table.scss';

@Renderer({
  name: 'crud-grid',
  desc: '...',
  test: /(?:^|\/)crud\/grid$/
})
@HocCrud({
  title: null,
  noPanel: true,
  className: '',
  hasBulkCheckbox: true
})
export default class Grid extends PureComponent {
  static propTypes = {
    bulkActions: PropTypes.arrayOf(PropTypes.shape({
      label: PropTypes.string.isRequired,
      actionType: PropTypes.string.isRequired
    })),
    className: PropTypes.string,
    draggable: PropTypes.bool,
    card: PropTypes.object.isRequired,
    rows: PropTypes.arrayOf(PropTypes.object),
    data: PropTypes.object,
    placeholder: PropTypes.string,
    loading: PropTypes.bool,

    // order by
    orderBy: PropTypes.string,
    orderDir: PropTypes.oneOf(['asc', 'desc']),

    // pagination
    currentPage: PropTypes.number.isRequired,
    lastPage: PropTypes.number.isRequired,
    perPage: PropTypes.number.isRequired,
    total: PropTypes.number.isRequired,

    showPageInfo: PropTypes.bool,

    // events
    onOrderByToggle: PropTypes.func,
    onPerPageChange: PropTypes.func,
    onPaginationChange: PropTypes.func,
    onBulkAction: PropTypes.func,
    onAction: PropTypes.func,
    onHighlight: PropTypes.func,
    onSaveOrder: PropTypes.func,
    onQuickSave: PropTypes.func
  };

  static defaultProps = {
    title: '表格',
    placeholder: '暂无数据',
    className: '',

    // pagination
    currentPage: 1, // 当前第几页
    lastPage: 1, // 总共有多少页
    perPage: 10, // 每页多少个
    total: 0, // 总共多少个

    switchPerPage: true, // 是否能切换页码
    // showPageInfo: true // 是否显示数据信息

    columnsCount: null,
    cardClassName: 'col-sm-6 col-md-4 col-lg-3'
  };

  constructor(props) {
    super(props);
  }

  render() {
    const rows = this.props.stateRows || [];
    const dragging = this.props.stateDragging;
    const {
      $path,
      data,
      placeholder,
      onAction,
      onHighlight,
      loading,
      card,
      locals,
      cardClassName,
      columnsCount,
      bulkActions,
      onNotify
    } = this.props;
    if (columnsCount && rows.length) {
      return (
        <div className="grid-wrapper">
          {padArr(rows, columnsCount).map((rows, i) => (
            <div className="row" key={i}>
              {rows.map((item, key) => {
                const body = render(`${$path}/card`, card, {
                  item,
                  data: assign({}, data, item),
                  onCheck: this.props.toggle,
                  onRequestAction: onAction,
                  onRequestHighlight: onHighlight,
                  onFieldValueChange: this.props.handleFieldValueChange,
                  onFieldValueSave: this.props.handleFieldValueSave,
                  disabled: loading,
                  disableQuickEdit: dragging || loading,
                  bulkActions,
                  onNotify,
                  locals: assign({},locals, item)
                });

                return (
                  <div key={item.$id} className={`col-md-${Math.round(12 / columnsCount)}`}>
                    <div
                      className={cx('card', {
                        'card-modified': item.$modified,
                        'card-highlight': item.$highlight,
                      })}
                    >
                      {body}
                    </div>
                  </div>
                );
              })}
            </div>
          ))}
        </div>
      )
    }

    return (
      <div className="grid-wrapper">
        <div className="row">
          {rows.length ? (rows.map((item, key) => {
            const body = render(`${$path}/card`, card, {
              item,
              data: assign({}, data, item),
              locals,
              onCheck: this.props.toggle,
              onRequestAction: onAction,
              onRequestHighlight: onHighlight,
              onFieldValueChange: this.props.handleFieldValueChange,
              onFieldValueSave: this.props.handleFieldValueSave,

              disabled: loading,
              disableQuickEdit: dragging || loading,
              bulkActions,
              onNotify,
              locals: assign({},locals, item)
            });

            return (
              <div key={item.$id} className={cardClassName}>
                <div
                  className={cx('card', {
                    'card-modified': item.$modified,
                    'card-highlight': item.$highlight
                  })}
                >
                  {body}
                </div>
              </div>
            );
          })) : (
            <div className="col-sm-12 container"><div className="text-muted">{placeholder}</div></div>
          )}
        </div>
      </div>
    );
  }
}